package com.ton.interceptor;

import com.kypj.frame.common.log.Log;
import com.ton.config.Perm;
import com.ton.config.data.AdminLoginUser;
import com.ton.utils.JWTUtil;
import com.ton.utils.auth.AuthUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.ton.config.annotation.Permission;
import com.ton.config.annotation.PermissionGuest;
import com.hai.admin.table.vo.Result;
import com.ton.utils.CacheUtil;
import com.ton.utils.ResponseUtil;
import com.kypj.frame.common.EmptyUtil;
import org.springframework.web.method.HandlerMethod;

import java.lang.reflect.Method;
import java.util.List;
@Component
public class AuthInterceptor implements HandlerInterceptor {

    @Autowired
    private AuthUtil authUtil;


    /*拦截器 对页面API进行鉴权 鉴权拦截器*/
    long accessNum = 0;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
//        response.addHeader("Access-Control-Allow-Origin", "*");
//        response.addHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS,DELETE,PUT");
//        response.setHeader("Access-Control-Allow-Headers", "mac,appId,access-token,Content-Type,user_token");
//        response.setHeader("Access-Control-Max-Age", "86400");
        String uri = request.getServletPath();


        String access_token = request.getHeader("access-token");
        Log.info("请求 >>>" + uri + "?" + request.getQueryString() + " header:access-token = " + access_token);
        AdminLoginUser loginUser = null;
        if (access_token != null && access_token.length() > 20) {
            loginUser = JWTUtil.verify(access_token, AdminLoginUser.class);
            if (loginUser != null) {
                request.setAttribute("admin_login_user", loginUser);
            }
        }

        if (handler instanceof HandlerMethod) {
            HandlerMethod method = (HandlerMethod) handler;
            Method md = method.getMethod();
            if (md.isAnnotationPresent(PermissionGuest.class)) {
                return true;
            }

            if (loginUser == null) {
                Result res = new Result();
                res.setErrorMsg("需要登录");
                res.setCode(400);
                ResponseUtil.writeJSON(res, response);
                return false;
            }
            String cacheKey = "admin_session_key_" + loginUser.getUserId();
            String key = CacheUtil.queryString(cacheKey);
            if (key == null || !key.equals(loginUser.getKey())) {
                Result res = new Result();
                res.setErrorMsg(key == null ? "登录超时，请重新登录" : "账号在其他地方登录");
                res.setCode(400);
                ResponseUtil.writeJSON(res, response);
                return false;
            }
            CacheUtil.cacheObject(cacheKey, key, 3600);

            List<String> permissions = CacheUtil.queryObject("admin_permission_" + loginUser.getUserId());
            if (permissions == null) {
                Result res = new Result();
                res.setErrorMsg("权限请求失败，请重新登录再试！");
                res.setCode(403);
                ResponseUtil.writeJSON(res, response);
                return false;
            }
            if (md.isAnnotationPresent(Permission.class)) {
                Permission perm = md.getAnnotation(Permission.class);
                if (null == perm.value() || "".equals(perm.value())) {
                    return true;
                }
                if (permissions.contains(Perm.super_permission)) {
                    return true;
                }
                String[] perms = perm.value().split(",");
                for (String p : perms) {
                    if (EmptyUtil.isNotEmpty(p) && permissions.contains(p)) {
                        return true;
                    }
                }
                Log.info("no permission:" + perm.value());
                Result res = new Result();
                res.setErrorMsg("没有权限访问");
                res.setCode(403);
                ResponseUtil.writeJSON(res, response);
                return false;
            } else {
                return true;
            }


        }
        return true;
    }
}
